//
//  HXDWebLoginViewController.swift
//  weibo
//
//  Created by huxuedong on 15/12/6.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit
import SVProgressHUD

let kAppKey = "1449069583"
//let kAppKey = "365653307"
let kAppSecret = "6815369cb7df3d42766e68a163e7dda9"
//let kAppSecret = "d80a91da1de8d701f533edd033d50683"

//授权回调页
let kRedirect_uri = "http://www.itheima.com/"

class HXDWebLoginViewController: UIViewController, UIWebViewDelegate {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        webView.delegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(kAppKey)&redirect_uri=\(kRedirect_uri)"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
    private func setupUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        navigationItem.title = "微博登录"
    }
    
    @objc private func dismiss() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill() {
        //设置自动填充的用户名和密码，用户名：yohtr35601@163.com，密码：qw1987
        let javaScriptString = "document.getElementById('userId').value='yohtr35601@163.com';document.getElementById('passwd').value='qw1987'"
//        let javaScriptString = "document.getElementById('userId').value='18768103944';document.getElementById('passwd').value='19820730LJhxd@'"
        webView.stringByEvaluatingJavaScriptFromString(javaScriptString)
    }
    
    //代理方法，webView加载请求的时候调用，判断是否加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //拦截回调页：如果是回调页，则拦截，并在回调地址里截取code，然后利用code去获得accessToken
        //absoluteString可以获取完整的URL字符串
        guard let url = request.URL?.absoluteString else {
            return true
        }
        //hasPrefix()用来判断以什么开头，如果请求的URL不是授权回调页，就加载该请求
        if !url.hasPrefix(kRedirect_uri) {
            return true
        }
        //截取URL中"?"之后的字符串(参数字符串)
        let parameter = request.URL?.query!
        if parameter!.hasPrefix("code=") {
            //截取code，从parameter中获取"code="之后的字符串
            let code = parameter?.substringFromIndex("code=".endIndex)
            //根据code获取accessToken
            HXDUserAccountViewModel.shareInstance.loadAccessToken(code!, complete: { (isSuccessed) -> () in
                if !isSuccessed {
                    SVProgressHUD.showErrorWithStatus("登录失败！")
                    return
                }
                SVProgressHUD.dismiss()
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName("switchVC", object: self)
                })
            })
        } else {
            dismiss()
        }
        return false
    }
    
    //代理方法，当开始加载webView时调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //代理方法，当webView加载完成时调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
